package com.hmall.gateway.fliters;


import cn.hutool.core.collection.CollUtil;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component // 将过滤器交给Spring管理
@RequiredArgsConstructor // 采用构造器注入(只会注入 final)
@EnableConfigurationProperties(AuthProperties.class) // 开启属性配置
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    // 注入Jwt工具类
    private final JwtTool jwtTool;

    // 注入配置文件中的属性
    private final AuthProperties authProperties;

    // **(重要) 路径匹配器,用于匹配路径是否在白名单中
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 登录校验开始
        //1. 获取request
        ServerHttpRequest request = exchange.getRequest();
        //2. 判断路径是否在白名单中
        if(isExclude(request.getURI().getPath())){
            // 无需拦截 直接放行
            return chain.filter(exchange);
        }
        //3. 获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get(HttpHeaders.AUTHORIZATION);
        if(!CollUtil.isEmpty(headers)){ // 请求头中存在token
            token = headers.get(0); // 获取token
        }
        //4. 解析并校验token
        Long userId = null;
        try{
            userId = jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            // 如果token无效，拦截返回401即可
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();  // 直接返回响应,不会再往下走了
        }
        //5. 如果有效，将userId放到请求头中，继续往下走
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("user-info",userInfo))
                .build();
        //6. 放行
        return chain.filter(ex);
    }

    /**
     * 判断路径是否在白名单中
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        for(String pathPattern : authProperties.getExcludePaths()){ // 遍历白名单
            if(antPathMatcher.match(pathPattern,path)) { // 如果路径匹配上了，则返回true
                return true;
            }
        }
        return false;
    }

    // 过滤器优先级，值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}

